package com.chushouya.manager.dao.repository;

import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import com.chushouya.manager.dao.entity.PartnerUserEntity;
import com.chushouya.manager.dao.mapper.PartnerUserEntityMapper;
import com.chushouya.manager.dto.admin.partner.PartnerUserQuery;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

/**
 * 合作商用户Repository
 */
@Repository
public class PartnerUserRepository extends BaseRepository<PartnerUserEntityMapper, PartnerUserEntity, Long> {

    private Example buildExample(PartnerUserQuery query) {
        final Example example = this.buildExample();
        if (Objects.nonNull(query.getAdminUserId())) {
            example.and().andEqualTo("adminUserId", query.getAdminUserId());
        }
        if (Objects.nonNull(query.getPartnerId())) {
            example.and().andEqualTo("partnerId", query.getPartnerId());
        }
        if (Strings.isNotEmpty(query.getPhone())) {
            example.and().andEqualTo("phone", query.getPhone());
        }
        if (Strings.isNotEmpty(query.getNickName())) {
            example.and().andEqualTo("nickName", query.getNickName());
        }
        if (Strings.isNotEmpty(query.getUserName())) {
            example.and().andEqualTo("userName", query.getUserName());
        }
        if (Objects.nonNull(query.getIsMaster())) {
            example.and().andEqualTo("isMaster", query.getIsMaster());
        }
        if (Objects.nonNull(query.getStatus())) {
            example.and().andEqualTo("status", query.getStatus());
        }
        return example;
    }

    public PartnerUserEntity selectOne(PartnerUserQuery query) {
        return this.selectFirstOneByExample(this.buildExample(query));
    }

    public void updateMerchantUserPhone(Long adminUserId, String phone) {
        PartnerUserEntity update = new PartnerUserEntity();
        update.setPhone(phone);
        update.setUserName(phone);
        update.setUpdateTime(Dates.getTimeNow());
        Example where = this.buildExample();
        where.and().andEqualTo("adminUserId", adminUserId);
        this.updateBySelective(update, where);
    }

    public PageResult<PartnerUserEntity> selectPageResult(PartnerUserQuery query) {
        return this.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public List<PartnerUserEntity> selectList(PartnerUserQuery query) {
        return this.selectByExample(this.buildExample(query));
    }

    public Boolean existsUserName(String userName) {
        final PartnerUserQuery query = new PartnerUserQuery();
        query.setUserName(userName);
        return this.selectCountByExample(this.buildExample(query)) > 0;
    }
}
